<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Level 2</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="./js/d3.v6.js"></script>
    <script type="text/javascript" src="./js/jquery.min.js"></script>
    <style>
        .inline_block{
            display: inline-block;
        }
        .ibutton{
            width: 130px;
            height: 40px;
            margin: 10px;
        }
        .heatmap{
            width:1400px;
            height:1000px;
        }
    </style>
</head>
<body>
    <div>
        <button class='ibutton' id='buttonMax'>Max</button>
        <button class='ibutton' id='buttonMin'>Min</button>
    </div>
    <div>
        <div id="heatmap" class='heatmap'></div>
        <div id="lineplot"></div>
    </div>

</body>
<script>
    $(function(){
        var margin = { top: 100, right: 50, bottom: 80, left: 100 },
            width = 1200 - margin.left - margin.right,
            height = 1000 - margin.top - margin.bottom,
            gridHeight = height / 12, // there are 12 months in a year
            gridMargin = { top: 3, right: 3, bottom: 3, left: 3 },
            legendSize = { height: 20, width: 600},
            gridPadding=1,
            months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec"];
        
        var svg = d3.select("#heatmap").append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
        
        var xScale = d3.scaleLinear();
        var yScale = d3.scalePoint();
        var colorScale = d3.scaleLinear();

        var color = d3.scaleSequential(d3.interpolateRdBu);

        // create tooltip
        var tooltip = d3.select("body")
            .append("div")
            .style("position", "absolute")
            .style("background-color", "snow")
            .style("padding", "2px")
            .style("z-index", "1")
            .style("visibility", "hidden")
            .text("a simple tooltip");
        // create title
        var title = svg.append("text")
            .attr("x", (width + margin.left + margin.right) / 2)             
            .attr("y", (margin.top / 2))
            .attr("text-anchor", "middle")  
            .style("font-size", "24px")
            .text(" Maximum Monthly Temperature of Hong Kong");
        
        // create chart
        var g = svg.append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
        

        var defs = svg.append("defs");
        defs.append("linearGradient")
            .attr("id", "linear-gradient")
            .selectAll("stop")
            .data(color.ticks().reverse().map((t, i, n) => {
                //console.log(t)
                return { offset: i/n.length, color: color(t) }
            } ))
            .enter().append("stop")
            .attr("offset", d => d.offset)
            .attr("stop-color", d => d.color);
        var legend = g.append('g')
            .attr("transform", "translate(0," + (height + 20 + legendSize.height) + ")")
        legend.append("rect")
            .attr("width", legendSize.width)
            .attr("height", legendSize.height)
            .style("fill", "url(#linear-gradient)");

        var grids;
        d3.csv('./data/temperature_daily.csv').then(function(data){
             //增广数据 便于后续数据处理
            var parseDate = d3.timeParse('%Y-%m-%d');
            var formatDate = d3.timeFormat('%Y-%m');
            data.forEach(function(e){
                var date = parseDate(e.date);
                e.year = date.getFullYear();
                e.month=months[date.getMonth()];
                e.day = date.getDate();
                e.ym=formatDate(date); 
            })
            data_5 = d3.filter(data,d=>{
                            return parseInt(d.year)>=2008
                    })
            t=d3.rollup(data_5, v => {
                //return d3.max(v,e=>{return parseInt(e.max_temperature)})
                return {"month": v[0].month, 
                        "year": v[0].year,
                        "max":d3.max(v,e=>{return parseInt(e.max_temperature)}),
                        "min":d3.min(v,e=>{return parseInt(e.min_temperature)}),
                        'days':v
                        };
            }, d => d.ym)
            dataArray=[]
            //console.log(t)
            t.forEach(e=>{dataArray.push(e)})
            //console.log(dataArray[1])
            data_5=dataArray;
            
            //console.log(data_5);
            var xRange = d3.extent(data_5.map(e => e.year));
            var minTemp = d3.min(data_5.map(e => e.min));
            var maxTemp = d3.max(data_5.map(e => e.max));
            var gridWidth = width / (xRange[1] - xRange[0] + 1);
            var minTemp = d3.min(data_5.map(e => e.min));
            var maxTemp = d3.max(data_5.map(e => e.max));

            xScale.domain(xRange).range([0+gridWidth/4, width-gridWidth/4 ]);
            yScale.domain(months).range([gridHeight/4, height - gridHeight/4]);
            colorScale.domain([minTemp,maxTemp]).range([0,legendSize.width ]);

            g.append("g")
            .attr("transform", "translate("+(gridWidth / 4 )+",0)")   
            .call(d3.axisTop(xScale).ticks(xRange[1] - xRange[0] + 1, d3.format("d")));

            g.append("g")
            .attr("transform", "translate(0,"+(gridHeight / 4 )+")")
            .call(d3.axisLeft(yScale));
            console.log(gridWidth)
            grids = g.append("g")
            .attr("transform", "translate("+gridMargin.left+","+gridMargin.top+")")
            .selectAll("rect")
            .data(data_5)
            .enter().append("rect")
            .attr("x", d => {
                //console.log('d.year:'+d.year)
                //console.log("xScale(d.year):"+xScale(d.year))
                //console.log("xScale(d.year) - gridWidth / 4 :"
                //+(xScale(d.year) - gridWidth / 4 ));
                return xScale(d.year) - gridWidth / 4
                })
            .attr("y", d => yScale(d.month) - gridHeight / 4 )
            .attr("width", gridWidth)
            .attr("height", gridHeight )
            .attr("fill", d => {
            
                return color(1 - (d.max-minTemp)/(maxTemp-minTemp));
            })
            .on('mouseover', function(e,d) {
                tooltip.style("visibility", "visible")
                .text("Date: " + d.year+" "+d.month + " max: " + d.max);
            })
            .on("mousemove", function(event){
                return tooltip.style("top", (event.pageY-12)+"px").style("left",(event.pageX+12)+"px");})
            .on("mouseout", function(){return tooltip.style("visibility", "hidden");});
            
                // Add X axis --> it is a date format
            var stroke_width=4;
            var x = d3.scaleLinear()
            .domain([1,31])
            .range([ 0+stroke_width, gridWidth-stroke_width]);
            
            
            // Add Y axis
            var y = d3.scaleLinear()
            .domain( [minTemp,maxTemp])
            .range([ gridHeight-stroke_width,0+stroke_width]);
            
            var lineMax = d3.line().x(function(d) { 
                //console.log(arguments);
                return x(d.day)
                //return 0;
            }).y(function(d) { 
                //return 0;
                return y( parseInt(d.max_temperature))
            });
            var lineMin = d3.line().x(function(d) { 
                //console.log(arguments);
                return x(d.day)
                //return 0;
            }).y(function(d) { 
                //return 0;
                return y(parseInt(d.min_temperature))
            });

            //console.log(line(data_5[0].days));
            //console.log(x(31))
            //console.log(y(a.max_temperature))
            //console.log(data_5[0].days)
            test=[]
            test.push(data_5[0])
            //console.log(test)
            //画折线
            g.append("g")
            .attr("transform", "translate("+gridMargin.left+","+gridMargin.top+")")
            .selectAll("path")
            .data(data_5)
            .enter()
            .append("path")
            .attr("d", function(d){ 
                //console.log(line(data_5[0].days))
                //console.log(d)
                if((d.month=='Sep')&(d.year==2017)){
                    console.log(d.days)
                }
                return lineMax(d.days);
             } )
            .attr("stroke", 'green')
            .style("stroke-width", stroke_width)
            .style("fill", "none")  
            .attr("transform", e=>{
                //console.log('e:')
                //console.log(e)
                //console.log(xScale(e.year))
                //xScale(d.year) - gridWidth / 4 + gridMargin.left
                return "translate("+ (xScale(e.year)- gridWidth / 4 )
                +","+(yScale(e.month)- gridHeight / 4 )
                +")"
            })
            
            g.append("g")
            .attr("transform", "translate("+gridMargin.left+","+gridMargin.top+")")
            .selectAll("path")
            .data(data_5)
            .enter()
            .append("path")
            .attr("d", function(d){ 
                //console.log(line(data_5[0].days))
                //console.log(d)
                return lineMin(d.days);
             } )
            .attr("stroke", 'grey')
            .style("stroke-width", stroke_width)
            .style("fill", "none")  
            .attr("transform", e=>{
                //console.log('e:')
                //console.log(e)
                //console.log(xScale(e.year))
                return "translate("+ (xScale(e.year)- gridWidth / 4 )
                +","+(yScale(e.month)- gridHeight / 4  )
                +")"
            })
            //console.log(colorScale.domain())
            //var colorRange = d3.extent(colorScale.range.map(e => e.year));
    
            colorAxis = legend.append('g')
                .attr("transform", "translate(0," + legendSize.height + ")")
                .call(d3.axisBottom(colorScale));
            function showMax() {
                title.text("Maximum Monthly Temperature of Hong Kong");
                grids
                .on('mouseover', function(e,d) {
                    tooltip.style("visibility", "visible")
                    .text("Date: " + d.year+" "+d.month + " max: " + d.max);
                })
                .transition().attr("fill", d => color(1 - (d.max-minTemp)/(maxTemp-minTemp)));
            }

            function showMin() {

                title.text("Minimum Monthly Temperature of Hong Kong");
                grids
                .on('mouseover', function(e,d) {
                    tooltip.style("visibility", "visible")
                    .text("Date: " + d.year+" "+d.month + " min: " + d.min);
                })
                .transition().attr("fill", d => color(1 - (d.min-minTemp)/(maxTemp-minTemp)));
            }
            $('#buttonMax').on('click',showMax);
            $('#buttonMin').on('click',showMin);
            $('#heatmap').toggle(showMin,showMax);
        })
            






    })
</script>
</html>